import json
import uuid
import asyncio
import aiohttp
import logging
from typing import Dict, List, Optional, Any
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, text
from datetime import datetime
from loguru import logger
from app.datatk.data_help import DataHelp

from app.models.db import UserSession, UserMsg, DataSet, DataField, ApiFunction, TaskConfig, Task
from app.services.task_service import TaskService


def json_serializer(obj):
    """JSON序列化器，处理datetime对象"""
    if isinstance(obj, datetime):
        return obj.isoformat()
    raise TypeError(f"Object of type {type(obj)} is not JSON serializable")


class TaskExecutionEngine:
    """任务执行引擎 - 根据意图识别结果执行不同类型的任务"""
    
    def __init__(self):
        self.current_user_id = None
        
    async def execute_task(
        self, 
        intent_result: Dict[str, Any], 
        session_id: str, 
        user_id: str,
        db: AsyncSession
    ) -> Dict[str, Any]:
        """
        执行单个任务
        
        参数:
            intent_result (Dict[str, Any]): 意图识别结果
            session_id (str): 会话ID
            user_id (str): 用户ID
            db (AsyncSession): 数据库会话
            
        返回:
            Dict[str, Any]: 执行结果
        """
        started_at = datetime.now()
        
        try:
            # 设置当前用户ID，供子方法使用
            self.current_user_id = user_id
            
            task_type = intent_result.get("intent_type")
            
            # 1. 先创建任务记录
            task = await TaskService.create_task_from_intent(
                intent_result, user_id, session_id, db
            )
            task_id = task.id
            logger.info(f"创建任务记录: {task_id} - {task.task_name}")
            
            # 2. 更新任务状态为执行中
            await TaskService.update_task_status(task_id, "running", db)
            
            # 3. 执行具体任务
            if task_type == "api_function":
                result = await self._execute_api_function(intent_result, db)
            elif task_type == "data_query":
                result = await self._execute_data_query(intent_result, db)
            elif task_type == "knowledge_query":
                result = await self._execute_knowledge_query(intent_result, db)
            else:
                result = {
                    "status": "error",
                    "message": f"不支持的任务类型: {task_type}。支持的类型: api_function, data_query, knowledge_query"
                }
            
            # 4. 保存任务执行结果到专门的结果表
            if task_id:
                result["started_at"] = started_at
                result["completed_at"] = datetime.now()
                await TaskService.save_execution_result(task_id, result, db)
            
          
            
            # 6. 添加任务ID到返回结果中
            result["task_id"] = task_id
            
            return result
            
        except Exception as e:
            logger.error(f"执行任务失败: {str(e)}")
            logger.exception(e)
            return {
                "status": "error",
                "message": f"任务执行失败: {str(e)}",
                "task_id": None
            }
    



    
    async def _get_task_result(self, task_id: str, db: AsyncSession) -> Optional[Dict[str, Any]]:
        """获取任务执行结果
        
        从任务表中获取指定任务的执行结果（合并表设计）
        """
        try:
            # 获取任务信息（包含执行结果）
            task = await TaskService.get_task_by_id(task_id, db)
            if not task:
                logger.warning(f"任务不存在: {task_id}")
                return None
            
            # 检查任务是否已完成并且成功
            if not task.is_completed() or not task.is_successful():
                logger.warning(f"任务执行结果不可用或失败: {task_id} - 状态: {task.status}, 执行状态: {task.execution_status}")
                return None
            
            # 构建返回结果
            return {
                "status": "success",
                "task_id": task_id,
                "task_name": task.task_name,
                "task_type": task.task_type,
                "result": task.get_result_data(),
                "execution_time": task.get_duration_seconds(),
                "completed_at": task.completed_at.isoformat() if task.completed_at else None,
                "rows_affected": task.rows_affected,
                "columns": task.get_columns_info()
            }
            
        except Exception as e:
            logger.error(f"获取任务结果失败: {task_id} - {str(e)}")
            return None
    
    async def _execute_api_function(
        self, 
        intent_result: Dict[str, Any], 
        db: AsyncSession
    ) -> Dict[str, Any]:
        """执行API函数调用"""
        try:
            api_function_id = intent_result.get("api_function_id")
            if not api_function_id:
                return {
                    "status": "error",
                    "message": "缺少API函数ID"
                }
            
            # 获取API函数配置
            api_query = select(ApiFunction).where(ApiFunction.id == api_function_id)
            api_result = await db.execute(api_query)
            api_function = api_result.scalar_one_or_none()
            
            if not api_function or not api_function.is_active:
                return {
                    "status": "error",
                    "message": "API函数不存在或已禁用"
                }
            
            # 检查必需参数
            required_params = api_function.required_params or []
            extracted_params = intent_result.get("extracted_params", {})
            missing_params = []
            
            for param in required_params:
                if param not in extracted_params or not extracted_params[param]:
                    missing_params.append(param)
            
            if missing_params:
                return {
                    "status": "need_params",
                    "message": f"缺少必需参数: {', '.join(missing_params)}",
                    "missing_params": missing_params,
                    "ask_questions": [f"请提供{param}参数" for param in missing_params]
                }
            
            # 执行API调用
            execution_result = await self._call_external_api(api_function, extracted_params)
            
            return {
                "status": "success",
                "task_type": "api_function",
                "function_name": api_function.function_name,
                "parameters": extracted_params,
                "result": execution_result
            }
            
        except Exception as e:
            logger.error(f"API函数执行失败: {str(e)}")
            return {
                "status": "error",
                "message": f"API函数执行失败: {str(e)}"
            }
    
    async def _execute_data_query(
        self, 
        intent_result: Dict[str, Any], 
        db: AsyncSession
    ) -> Dict[str, Any]:
        """执行数据查询 - 增强数据量控制"""
        try:
            from config import MAX_QUERY_ROWS, DATA_LIMITS
            
            dataset_id = intent_result.get("dataset_id")
            generated_sql = intent_result.get("generated_sql")
            query_style = intent_result.get("query_style", "analytical")
            response_style = intent_result.get("response_style", "full_analysis")
            
            if not generated_sql:
                return {
                    "status": "error",
                    "message": "缺少AI生成的SQL语句，无法执行查询"
                }

            # 获取数据集信息
            dataset_query = select(DataSet).where(DataSet.id == dataset_id or DataSet.name == dataset_id)
            dataset_result = await db.execute(dataset_query)
            dataset = dataset_result.scalar_one_or_none()
            
            if not dataset:
                return {
                    "status": "error",
                    "message": "数据集不存在"
                }

            # 🎯 核心改进：根据查询样式和DATA_LIMITS设置智能数据量限制
            if query_style == "simple" and response_style == "data_only":
                # 简单查询：用户主要关心数据完整性，使用最大显示限制
                max_rows = min(MAX_QUERY_ROWS, DATA_LIMITS["sample_display"])
            else:
                # 分析查询：重点是分析质量，使用压缩显示限制
                max_rows = min(MAX_QUERY_ROWS, DATA_LIMITS["compressed_display"])
            
            logger.info(f"执行SQL查询 - Style: {query_style}, Limit: {max_rows}")
            
            # 使用DatasetService.execute_sql_from_source执行SQL（带限制）
            from app.services.dataset_service import DatasetService
            
            query_result = await DatasetService.execute_sql_from_source(
                datasourceid=dataset.data_source_id,
                sql_statement=generated_sql,
                session=db,
                max_rows=max_rows,
                enable_limit=True
            )
            
            if not query_result.get("status"):
                return {
                    "status": "error",
                    "message": query_result.get("message", "查询执行失败")
                }
            
            # 获取查询结果
            raw_data = query_result.get("data", [])
            columns = query_result.get("columns", [])
            is_truncated = query_result.get("truncated", False)
            total_rows_returned = query_result.get("total_rows_returned", len(raw_data))
            total_rows_estimated = query_result.get("total_rows_estimated")
            
            # 🎯 新增：根据DATA_LIMITS实现智能数据处理策略
            display_strategy = self._determine_display_strategy(total_rows_returned, DATA_LIMITS)
            processed_data = self._process_data_by_strategy(raw_data, display_strategy, DATA_LIMITS)
            
            # 🎯 构建用户友好的截断信息
            data_info = {
                "total_rows_returned": total_rows_returned,
                "is_truncated": is_truncated,
                "display_strategy": display_strategy,
                "truncation_info": None
            }
            
            if is_truncated:
                if total_rows_estimated and str(total_rows_estimated).isdigit():
                    data_info["truncation_info"] = {
                        "total_estimated": total_rows_estimated,
                        "returned": total_rows_returned,
                        "truncated_count": total_rows_estimated - total_rows_returned,
                        "message": f"⚠️ 数据已截断：查询共发现 {total_rows_estimated} 条记录，返回前 {total_rows_returned} 条 ({display_strategy})"
                    }
                else:
                    data_info["truncation_info"] = {
                        "total_estimated": "未知",
                        "returned": total_rows_returned,
                        "message": f"⚠️ 数据可能已截断：返回 {total_rows_returned} 条记录，可能还有更多数据 ({display_strategy})"
                    }
            
            # 🎯 根据显示策略调整用户消息
            user_message = self._generate_user_message(total_rows_returned, is_truncated, display_strategy, data_info)
            
            # 构建返回结果
            result = {
                "status": "success",
                "task_type": "data_query",
                "dataset_name": dataset.name,
                "dataset_id": dataset_id,
                "sql_query": generated_sql,
                "sql_source": "ai_generated",
                "query_style": query_style,
                "response_style": response_style,
                "columns": columns,
                "data": processed_data,  # 使用处理后的数据
                "user_message": user_message,
                **data_info
            }
            
            logger.info(f"数据查询执行成功: {total_rows_returned} 条记录，截断: {is_truncated}，策略: {display_strategy}")
            return result
            
        except Exception as e:
            logger.error(f"数据查询执行失败: {str(e)}")
            return {
                "status": "error",
                "message": f"数据查询执行失败: {str(e)}"
            }

    def _determine_display_strategy(self, row_count: int, data_limits: Dict[str, int]) -> str:
        """根据数据量确定显示策略"""
        if row_count <= data_limits["direct_display"]:
            return "direct_display"
        elif row_count <= data_limits["compressed_display"]:
            return "compressed_display"
        elif row_count <= data_limits["sample_display"]:
            return "sample_display"
        else:
            return "no_display"
    
    def _process_data_by_strategy(self, data: List[Dict], strategy: str, data_limits: Dict[str, int]) -> List[Dict]:
        """根据显示策略处理数据"""
        if strategy == "direct_display":
            # 直接显示所有数据
            return data
        elif strategy == "compressed_display":
            # 压缩显示：保留前80%的数据
            limit = int(data_limits["compressed_display"] * 0.8)
            return data[:limit]
        elif strategy == "sample_display":
            # 采样显示：显示头部、中部、尾部的代表性数据
            total = len(data)
            if total <= data_limits["direct_display"]:
                return data
            
            # 保留前200条、中间100条、最后200条
            head_count = min(200, total // 3)
            middle_count = min(100, total // 3)
            tail_count = min(200, total // 3)
            
            head_data = data[:head_count]
            middle_start = (total - middle_count) // 2
            middle_data = data[middle_start:middle_start + middle_count]
            tail_data = data[-tail_count:]
            
            # 添加采样标记
            sampled_data = head_data + [{"__sampling_marker__": f"... 省略中间 {total - head_count - middle_count - tail_count} 条记录 ..."}] + middle_data + [{"__sampling_marker__": f"... 省略部分记录 ..."}] + tail_data
            return sampled_data
        else:  # no_display
            # 不显示具体数据，只返回汇总信息
            return [{
                "__summary__": f"数据量过大({len(data)}条)，不显示具体内容",
                "__suggestion__": "请使用更具体的筛选条件来缩小查询范围"
            }]
    
    def _generate_user_message(self, row_count: int, is_truncated: bool, strategy: str, data_info: Dict) -> str:
        """根据显示策略生成用户消息"""
        base_msg = f"✅ 查询完成，共返回 {row_count} 条数据"
        
        if strategy == "direct_display":
            if is_truncated:
                return f"{base_msg}。{data_info['truncation_info']['message']}。"
            else:
                return f"{base_msg}，数据完整显示。"
        elif strategy == "compressed_display":
            return f"{base_msg}，采用压缩显示（显示约80%数据）。如需完整数据，请添加筛选条件。"
        elif strategy == "sample_display":
            return f"{base_msg}，采用采样显示（显示头部、中部、尾部代表性数据）。如需完整数据，请添加筛选条件。"
        else:  # no_display
            return f"{base_msg}，数据量过大不显示具体内容。请使用更具体的筛选条件来缩小查询范围。"
    

    
    async def _call_external_api(
        self, 
        api_function: ApiFunction, 
        parameters: Dict[str, Any]
    ) -> Dict[str, Any]:
        """调用外部API"""
        try:
            # 准备请求参数
            url = api_function.endpoint_url
            method = api_function.http_method.upper()
            headers = api_function.headers or {}
            timeout = api_function.timeout or 30
            
            # 处理认证配置
            auth_config = api_function.auth_config or {}
            if auth_config.get("type") == "bearer":
                headers["Authorization"] = f"Bearer {auth_config.get('token')}"
            elif auth_config.get("type") == "api_key":
                headers[auth_config.get("header_name", "X-API-Key")] = auth_config.get("api_key")
            
            # 发起HTTP请求
            async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=timeout)) as session:
                if method == "GET":
                    async with session.get(url, headers=headers, params=parameters) as response:
                        result = await self._process_api_response(response, api_function)
                elif method == "POST":
                    async with session.post(url, headers=headers, json=parameters) as response:
                        result = await self._process_api_response(response, api_function)
                else:
                    return {
                        "status": "error",
                        "message": f"不支持的HTTP方法: {method}"
                    }
            
            return result
            
        except asyncio.TimeoutError:
            return {
                "status": "error",
                "message": "API调用超时"
            }
        except Exception as e:
            logger.error(f"API调用失败: {str(e)}")
            return {
                "status": "error",
                "message": f"API调用失败: {str(e)}"
            }
    
    async def _process_api_response(
        self, 
        response: aiohttp.ClientResponse, 
        api_function: ApiFunction
    ) -> Dict[str, Any]:
        """处理API响应"""
        try:
            if response.status == 200:
                try:
                    response_data = await response.json()
                except:
                    response_data = await response.text()
                
                return {
                    "status": "success",
                    "status_code": response.status,
                    "data": response_data
                }
            else:
                error_text = await response.text()
                return {
                    "status": "error",
                    "status_code": response.status,
                    "message": f"API返回错误状态: {response.status}",
                    "error_detail": error_text
                }
                
        except Exception as e:
            return {
                "status": "error",
                "message": f"处理API响应失败: {str(e)}"
            }
    

    
    async def save_tasks_summary_message(
        self,
        execution_results: List[Dict[str, Any]],
        session_id: str,
        user_id: str,
        db: AsyncSession
    ):
        """
        保存任务执行汇总消息
        
        参数:
            execution_results: 所有任务的执行结果列表
            session_id: 会话ID
            user_id: 用户ID
            db: 数据库会话
        """
        try:
            # 统计执行结果
            total_tasks = len(execution_results)
            success_count = sum(1 for r in execution_results if r.get("status") == "success")
            failed_count = total_tasks - success_count
            
            # 生成汇总消息
            if failed_count == 0:
                summary_message = f"✅ 所有任务执行完成！共完成 {total_tasks} 个任务"
            else:
                summary_message = f"📊 任务执行完成：成功 {success_count} 个，失败 {failed_count} 个"
            
            # 构建详细的任务执行信息
            task_details = []
            query_results = []  # 收集数据查询结果
            
            for result in execution_results:
                task_type = result.get("task_type", "unknown")
                task_name = result.get("task_name", "未知任务")
                
                if result.get("status") == "success":
                    if task_type == "data_query":
                        total_rows = result.get("total_rows", 0)
                        task_details.append(f"• {task_name}：查询成功，获得 {total_rows} 条数据")
                        
                        # 收集查询结果用于后续分析
                        if result.get("data"):
                            query_results.append({
                                "task_name": task_name,
                                "data": result.get("data", []),
                                "dataset_name": result.get("dataset_name", ""),
                                "sql_query": result.get("sql_query", "")
                            })
                    elif task_type == "api_function":
                        task_details.append(f"• {task_name}：执行成功")
                    else:
                        task_details.append(f"• {task_name}：执行成功")
                else:
                    error_msg = result.get("message", "未知错误")
                    task_details.append(f"• {task_name}：执行失败 - {error_msg}")
            
            # 构建完整消息内容
            full_message = summary_message
            if task_details:
                full_message += "\n\n" + "\n".join(task_details)
            
            # 构建消息数据（包含查询结果等信息）
            message_data = {
                "summary": {
                    "total_tasks": total_tasks,
                    "success_count": success_count,
                    "failed_count": failed_count
                },
                "task_results": execution_results,
                "query_results": query_results
            }
            
            # 保存汇总消息
            response_msg = UserMsg(
                id=str(uuid.uuid4()),
                user_id=user_id,
                session_id=session_id,
                message=full_message,
                message_type="system",
                message_data= DataHelp.to_json(message_data),
                timestamp=datetime.now()
            )
            
            db.add(response_msg)
            await db.commit()
            
            logger.info(f"保存任务汇总消息成功: {total_tasks}个任务，成功{success_count}个")
            
        except Exception as e:
            logger.error(f"保存任务汇总消息失败: {str(e)}")
            await db.rollback()
    



    
    def _generate_section_title_from_task_name(self, task_name: str, section_number: int) -> str:
        """从任务名称生成报告章节标题"""
        try:
            if not task_name:
                return f"{section_number}. 数据分析"
            
            # 提取关键信息，生成简洁的标题
            if "专业分布" in task_name:
                return f"{section_number}. 专业分布分析"
            elif "性别分布" in task_name:
                return f"{section_number}. 性别构成分析"
            elif "地区分布" in task_name:
                return f"{section_number}. 地区分布分析"
            elif "年龄分布" in task_name:
                return f"{section_number}. 年龄结构分析"
            else:
                # 通用处理：移除"查询"、"2024级"等词汇
                clean_name = task_name.replace("查询", "").replace("2024级", "").replace("新生", "").strip()
                if clean_name:
                    return f"{section_number}. {clean_name}分析"
                else:
                    return f"{section_number}. 数据分析"
                    
        except Exception as e:
            logger.error(f"生成章节标题失败: {str(e)}")
            return f"{section_number}. 数据分析"
    
    def _generate_query_summary(self, query_result: Dict[str, Any]) -> str:
        """生成查询结果摘要"""
        try:
            data = query_result.get("data", [])
            task_name = query_result.get("task_name", "数据查询")
            total_rows = query_result.get("total_rows", len(data))
            
            if total_rows == 0:
                return "暂无数据"
            
            # 生成基本统计摘要
            summary_parts = [f"本次{task_name}共获取{total_rows}条数据"]
            
            # 如果数据有明显的分布特征，添加到摘要中
            if data and len(data) > 0:
                first_item = data[0]
                if isinstance(first_item, dict) and len(first_item) >= 2:
                    keys = list(first_item.keys())
                    if len(keys) >= 2:
                        # 假设第二个字段是数值字段（通常是count）
                        value_key = keys[1]
                        values = [item.get(value_key, 0) for item in data if isinstance(item.get(value_key), (int, float))]
                        if values:
                            total = sum(values)
                            max_value = max(values)
                            max_item = next((item for item in data if item.get(value_key) == max_value), None)
                            if max_item and len(keys) >= 1:
                                category_key = keys[0]
                                max_category = max_item.get(category_key, "未知")
                                summary_parts.append(f"，总计{total}个，其中{max_category}最多({max_value}个)")
            
            return "。".join(summary_parts) + "。"
            
        except Exception as e:
            logger.error(f"生成查询摘要失败: {str(e)}")
            return "数据查询完成。"
    
    def _generate_report_summary(self, report_sections: List[Dict[str, Any]], report_type: str, total_data_points: int) -> str:
        """生成报告摘要"""
        try:
            if not report_sections:
                return "报告生成完成，但没有可用的数据章节。"
            
            sections_count = len(report_sections)
            sections_with_data = len([s for s in report_sections if s.get("data_count", 0) > 0])
            
            summary_parts = [
                f"本{report_type}共包含{sections_count}个分析章节",
                f"其中{sections_with_data}个章节包含有效数据",
                f"总计{total_data_points}条数据记录"
            ]
            
            # 如果有数据，添加主要发现
            if sections_with_data > 0 and report_sections:
                # 找到数据最多的章节
                max_data_section = max(
                    (s for s in report_sections if s.get("data_count", 0) > 0),
                    key=lambda x: x.get("data_count", 0),
                    default=None
                )
                if max_data_section:
                    section_title = max_data_section.get("section_title", "某个章节")
                    data_count = max_data_section.get("data_count", 0)
                    summary_parts.append(f"，{section_title}包含最多数据({data_count}条)")
            
            return "。".join(summary_parts) + "。"
            
        except Exception as e:
            logger.error(f"生成报告摘要失败: {str(e)}")
            return f"{report_type}生成完成。"
    
    async def _execute_knowledge_query(
        self, 
        intent_result: Dict[str, Any], 
        db: AsyncSession
    ) -> Dict[str, Any]:
        """执行知识库查询"""
        try:
            query_text = intent_result.get("query_text")
            search_keywords = intent_result.get("search_keywords", [])
            knowledge_category = intent_result.get("knowledge_category")
            generated_sql = intent_result.get("generated_sql")
            
            if not query_text:
                return {
                    "status": "error",
                    "message": "缺少查询问题，无法执行知识库查询"
                }
            
            if not generated_sql:
                return {
                    "status": "error",
                    "message": "缺少知识库查询SQL语句"
                }
            
            logger.info(f"执行知识库查询: {query_text}")
            logger.info(f"执行SQL: {generated_sql}")
            
            # 执行SQL查询
            result = await db.execute(text(generated_sql))
            rows = result.fetchall()
            
            # 转换查询结果
            results = []
            for row in rows:
                row_dict = dict(row._mapping)
                results.append({
                    'title': row_dict.get('title', ''),
                    'content': row_dict.get('content', ''),
                    'knowledge_base': row_dict.get('knowledge_base_name', ''),
                    'category': row_dict.get('category', knowledge_category or ''),
                    'keywords': row_dict.get('keywords', ''),
                    'priority': row_dict.get('priority', 0),
                    'view_count': row_dict.get('view_count', 0),
                    'relevance_score': 0.8  # 默认相关性评分
                })
            
            # 构建搜索结果
            search_result = {
                'success': True,
                'total_results': len(results),
                'results': results,
                'search_keywords': search_keywords
            }
            
            # 格式化返回结果
            formatted_answer = self._format_knowledge_answer(search_result, query_text)
            
            result = {
                "status": "success",
                "task_type": "knowledge_query",
                "query_text": query_text,
                "search_keywords": search_keywords,
                "knowledge_category": knowledge_category,
                "total_results": len(results),
                "results": results,
                "answer": formatted_answer,
                "sources": results,
                "confidence": 0.9,
                "user_message": formatted_answer
            }
            
            logger.info(f"知识库查询执行成功: {query_text}，找到{len(results)}个结果")
            return result
            
        except Exception as e:
            logger.error(f"知识库查询执行失败: {str(e)}")
            return {
                "status": "error",
                "message": f"知识库查询执行失败: {str(e)}"
            }
    
    def _format_knowledge_answer(self, search_result: Dict[str, Any], query_text: str) -> str:
        """格式化知识库搜索结果为用户友好的答案"""
        try:
            results = search_result.get('results', [])
            total_results = search_result.get('total_results', 0)
            
            if total_results == 0:
                return f"很抱歉，没有找到关于\"{query_text}\"的相关知识。您可以尝试使用不同的关键词进行搜索，或联系管理员添加相关知识内容。"
            
            # 构建答案
            answer_parts = []
            answer_parts.append(f"根据您的查询\"{query_text}\"，我找到了以下相关信息：\n")
            
            # 显示最相关的结果（最多3个）
            top_results = results[:3]
            for i, result in enumerate(top_results, 1):
                answer_parts.append(f"**{i}. {result['title']}**")
                answer_parts.append(f"来源：{result['knowledge_base']} - {result['category']}")
                
                # 显示摘要或内容预览
                content = result.get('summary') or result.get('content_preview', '')
                if content:
                    answer_parts.append(f"{content}")
                
                answer_parts.append(f"相关性评分：{result['relevance_score']} | 查看次数：{result['view_count']}\n")
            
            # 如果有更多结果，提示用户
            if total_results > 3:
                answer_parts.append(f"\n还有 {total_results - 3} 个相关结果。如需查看更多详细信息，请使用更具体的关键词进行搜索。")
            
            # 添加搜索关键词信息
            search_keywords = search_result.get('search_keywords', [])
            if search_keywords:
                answer_parts.append(f"\n搜索关键词：{', '.join(search_keywords)}")
            
            return "\n".join(answer_parts)
            
        except Exception as e:
            logger.error(f"格式化知识库答案失败: {str(e)}")
            return f"找到了 {search_result.get('total_results', 0)} 个相关结果，但格式化答案时出现错误。请查看原始搜索结果。"

